package com.lnw.service;

import com.lnw.dao.UserDAO;
import com.lnw.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class UserServiceImpl implements UserService{

    @Autowired
    private UserDAO userDAO;

    /**
     * 注册
     * @param user
     */
    public void register(User user){
        if (user.getUsername()==null){
            throw new RuntimeException("用户名不能为空");
        }
        else if (user.getPassword()==null){
            throw new RuntimeException("密码不能为空");
        }
        else if(userDAO.findByUserName(user.getUsername())==null){
            userDAO.save(user);
        }else{
            throw new RuntimeException("用户名已存在");
        }
    }

    /**
     * 登录
     * @param user
     * @return
     */
    @Override
    public User login(User user) {
        User findUser = userDAO.findByUserName(user.getUsername());
        if (findUser!=null){
            if (findUser.getPassword().equals(user.getPassword())){
                //登录成功
                return findUser;
            }else{
                throw new RuntimeException("密码错误");
            }
        }else{
            throw new RuntimeException("用户名错误");
        }
    }

    @Override
    public User findByUserId(String id) {
        return userDAO.findByUserId(id);
    }

}
